package com.photo.controller;

import com.photo.bean.Record;
import com.photo.config.ConstConfig;
import com.photo.dao.RecordMapper;
import com.photo.utils.DateUtils;
import top.hserver.core.interfaces.HttpRequest;
import top.hserver.core.interfaces.HttpResponse;
import top.hserver.core.ioc.annotation.Autowired;
import top.hserver.core.ioc.annotation.Controller;
import top.hserver.core.ioc.annotation.GET;
import top.hserver.core.ioc.annotation.POST;
import top.hserver.core.server.context.PartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author hxm
 */

@Controller
public class IndexController {

    @Autowired
    private RecordMapper recordMapper;

    @GET("/")
    public void index(HttpRequest request, HttpResponse response) {
        List<Record> select = recordMapper.createLambdaQuery().select();
        Map<String, Object> hashMap = new HashMap<>(1);
        hashMap.put("record", select);
        response.sendTemplate("/index.ftl", hashMap);
    }

    @GET("/add")
    public void add(HttpRequest request, HttpResponse response) {
        response.sendTemplate("/add.ftl");
    }

    @GET("/imgs{p}")
    public void imgs(String p, HttpResponse response) {
        response.setDownloadFile(new File(ConstConfig.PHOTO_PATH + p));
    }

    @POST("/upload")
    public void upload(Record record, HttpRequest request, HttpResponse response) throws IOException {
        PartFile file = request.queryFile("file");
        String s = "a" + UUID.randomUUID().toString().replace("-", "");
        if (file != null && !file.extName().equals("")) {
            file.moveTo(new File(ConstConfig.PHOTO_PATH + s + "." + file.extName()));
            record.setImg("imgs/" + s + "." + file.extName());
            record.setId(s);
            record.setCreateTime(DateUtils.nowTime());
            recordMapper.insert(record);
        }
        response.sendTemplate("/add.ftl");
    }
}
